﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Areas.Organization.Controllers
{
    public class CustomerController : BaseController
    {
        public ICustomerContract CustomerContract { get; set; }
        public ICustomerPhoneContract CustomerPhoneContract { get; set; }
        public IUsersContract UsersContract { get; set; }
        public IIntermediaryContract IntermediaryContract { get; set; } 
        [Description("客户列表")]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult IndexAsync(int pageIndex, int pageSize, string search = "")
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var agentid = model.AgentId;
            var query = from ctc in CustomerContract.Entities.Where(m => !m.IsDeleted)
                        join u in UsersContract.Entities.Where(m => !m.IsDeleted)
                        on ctc.UserID equals u.Id
                        join i in IntermediaryContract.Entities.Where(m => !m.IsDeleted)
                        on u.IntermediaryID equals i.Id
                        where i.AgentID == agentid
                        select new
                        {
                            Id = ctc.Id,
                            Name = ctc.Name,
                            Remark = ctc.Remark,
                            Sex = ctc.Sex == 0 ? "男" : "女", 
                            User = u.Name,
                            CreatedTime = ctc.CreatedTime,
                            Intermediary = i.Name
                        }; 
            if (search!="")
            {
                query = query.Where(m=>m.Name.Contains(search));
            }
            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.CreatedTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : query;

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        [AjaxOnly]
        public ActionResult PhoenList(int id)
        {
            //获取省份数据   
            var query = CustomerPhoneContract.Entities.Where(m=>m.CustomerID==id);
            var a = query.ToList();
            return JsonEx(query.ToList(), JsonRequestBehavior.AllowGet);
        }
    }
}